package com.sc.auction.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.auction.common.exception.AuctionException;
import com.sc.auction.common.jwt.JwtInfo;
import com.sc.auction.common.jwt.JwtUtils;
import com.sc.auction.common.util.R;
import com.sc.auction.common.util.ResultCode;
import com.sc.auction.user.pojo.User;
import com.sc.auction.user.service.UserService;
import com.sc.auction.user.vo.UserQuery;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author theTi
 * @since 2020-09-01
 */
@RestController
@RequestMapping("/user/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @ApiOperation("增加用户")
    @PostMapping(value = "/addUser")
    public R addUser(User user) throws AuctionException{
        boolean flag=false;
        if(user!=null){
            user.setCreationDate(new Date());
            flag=userService.save(user);
        }
        if(flag){
            return R.ok();
        }else {
            throw new AuctionException(201,"增加失败");
        }
    }

    @ApiOperation("用户认证")
    @GetMapping("/login")
    public R login(UserQuery user) throws AuctionException{
        System.out.println(user);
        String token=userService.login(user);
        if(token!=null&&!token.isEmpty()){
            redisTemplate.opsForValue().set(user.getUsername(),token,30, TimeUnit.MINUTES);
            return R.ok().message("登录成功").data("token",token);
        }else {
            throw new AuctionException(ResultCode.ERROR,"验证失败");
        }
    }
    @ApiOperation("用户认证 手机号码方式登录")
    @GetMapping("/telephoneLogin")
    public R telephoneLogin(String phone,String code) throws AuctionException{
        QueryWrapper queryWrapper = new QueryWrapper();
        if(phone!=null&&!phone.isEmpty()){
            queryWrapper.eq("telephone",phone);
        }
        String redisCode=redisTemplate.opsForValue().get(phone);
        redisCode=redisCode.replace("\"","");
        User user=null;
        String  token=null;

        if(redisCode.equals(code)){
            user = userService.getOne(queryWrapper);
        }
        if(user!=null){
            JwtInfo jwtInfo = new JwtInfo();
            jwtInfo.setUserCode(user.getUsername());
            jwtInfo.setId(user.getId());
            token= JwtUtils.genJwt(jwtInfo);
        }
        if(token!=null&&!token.isEmpty()){
            redisTemplate.opsForValue().set(user.getUsername(),token,30, TimeUnit.MINUTES);
            return R.ok().message("登录成功").data("token",token);
        }else {
            throw new AuctionException(ResultCode.ERROR,"验证失败");
        }
    }
    @PutMapping(value = "/update")
    @ApiOperation("根据id修改用户信息")
    public R update(@RequestBody User user) {
        System.out.println(user);
        boolean flag=false;
        if (user != null && user.getId() != null) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("id", user.getId());
            user.setModifyDate(new Date());
            flag = userService.update(user, queryWrapper);
        }
        if (flag) {
            return R.ok();
        } else {
            return R.error();
        }
    }
    @ApiOperation("根据id删除user")
    @DeleteMapping(value = "/deleteUserById")
    public R deleteUserById(Integer id){
        boolean flag=false;
        if(id!=null&&id!=0){
            flag=userService.removeById(id);
        }
        if (flag) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @GetMapping(value = "/getUserById")
    @ApiOperation("根据用户id查询用户信息")
    public R getUserById(@RequestParam("id") Integer id)throws AuctionException{
        User user=userService.getById(id);
        if(user!=null){
            return R.ok().data("user",user);
        }else {
            throw new AuctionException(ResultCode.ERROR,"查询失败");
        }
    }
    @ApiOperation("根据token获取登录信息")
    @GetMapping(value = "/getlogininfo")
    public R getLoginInfo(String token)throws AuctionException{
        try {
            Claims claims = JwtUtils.checkJwt(token);
            JwtInfo jwtInfo = new JwtInfo();
            return R.ok().data("userInfo",claims.get("userCode")).data("id",claims.get("id"));
        } catch (Exception e) {
            throw new AuctionException(ResultCode.ERROR,"解析用户信息失败");
        }
    }
    @GetMapping(value = "/findAllUser")
    @ApiOperation("查询所有用户或根据用户名模糊查询")
    public R findAllUser(@ApiParam(name = "page",defaultValue = "1",required = true)@RequestParam("page") Integer page,
                         @ApiParam(name = "limit",defaultValue = "5",required = true)@RequestParam("limit") Integer limit,
                         UserQuery user) throws AuctionException{
        Page<User> pageBean=new Page<>(page,limit);
        QueryWrapper queryWrapper=null;
        if(user!=null) {
            queryWrapper = new QueryWrapper();
            if(user.getUsername()!=null&&!user.getUsername().isEmpty()){
                //queryWrapper.eq("username",user.getUsername());
                queryWrapper.like("username",user.getUsername());
            }
        }
        userService.page(pageBean,queryWrapper);
        List<User> records = pageBean.getRecords();
        long total = pageBean.getTotal();

        if (records!=null&&records.size()>0){
            return R.ok().data("total",total).data("records",records);
        }else {
            return R.error();
        }
    }

    @PutMapping(value = "/cofirmTelphone")
    @ApiOperation("手机号码验证")
    public R confirmTelphone(String phone,String checkcode,@RequestBody User user) throws AuctionException {
        String redisCode=redisTemplate.opsForValue().get(phone);
        redisCode=redisCode.replace("\"","");
        if(redisCode.equals(checkcode)){
            if(user!=null){
                user.setTelephone(phone);
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("id",user.getId());
                boolean update = userService.update(user, queryWrapper);
                if(update){
                    return R.ok().code(200).message("手机号码验证成功");
                }else{
                    return R.ok().code(201).message("手机号码验证失败");
                }
            }
        }else{
            throw new AuctionException(200,"验证码输入错误");
        }
        return null;
    }





}

